﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace JESAI.DynamicWebApi.Helpers
{
    /// <summary>
    /// 反射帮助类
    /// </summary>
    internal static class ReflectionHelper
    {
        /// <summary>
        /// 尝试获取为类成员定义的of属性，该属性声明的类型包括继承的属性。
        /// 如果根本没有声明，则返回默认值。
        /// </summary>
        /// <typeparam name="TAttribute">属性的类型</typeparam>
        /// <param name="memberInfo">MemberInfo成员</param>
        /// <param name="defaultValue">默认值（默认为空）</param>
        /// <param name="inherit">从基类继承属性</param>
        public static TAttribute GetSingleAttributeOrDefault<TAttribute>(MemberInfo memberInfo, TAttribute defaultValue = default(TAttribute), bool inherit = true)
            where TAttribute : Attribute
        {
            //Get attribute on the member
            if (memberInfo.IsDefined(typeof(TAttribute), inherit))
            {
                return memberInfo.GetCustomAttributes(typeof(TAttribute), inherit).Cast<TAttribute>().First();
            }

            return defaultValue;
        }

        /// <summary>
        ///获取成员的单个属性。
        /// </summary>
        /// <typeparam name="TAttribute">属性的类型</typeparam>
        /// <param name="memberInfo">将检查属性的成员</param>
        /// <param name="inherit">包含继承的属性</param>
        /// <returns>如果找到，则返回属性对象。如果找不到，则返回null。</returns>
        public static TAttribute GetSingleAttributeOrNull<TAttribute>(this MemberInfo memberInfo, bool inherit = true)
            where TAttribute : Attribute
        {
            if (memberInfo == null)
            {
                throw new ArgumentNullException(nameof(memberInfo));
            }

            var attrs = memberInfo.GetCustomAttributes(typeof(TAttribute), inherit).ToArray();
            if (attrs.Length > 0)
            {
                return (TAttribute)attrs[0];
            }

            return default(TAttribute);
        }
    }
}
